package io.github.libkodi.basic_gateway.tools;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;

public class ValueUtils {
	public static Future<JsonObject> values(JsonObject data, String keys) {
		return Future.future(promise -> {
			JsonObject res = new JsonObject();
			Pattern patt = Pattern.compile("[^\s]+");
			Matcher m = patt.matcher(keys);
			
			try {
				Object val;
				
				while (m.find()) {
					val = get(data, m.group());
					
					if (val != null) {
						res.put(m.group(), val);
					}
				}
				
				promise.complete(res);
			} catch (Exception e) {
				promise.fail(e);
			}
		});
	}

	private static Pattern keyPattern = Pattern.compile("^(\\w[^\\[\\]\\.]+)(?:\\[(\\d+)\\]|)");
	
	@SuppressWarnings("unchecked")
	public static <T> T get(JsonObject data, String key, Class<T> type) {
		return (T)get(data, key);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T get(Map<String, Object> data, String key, Class<T> type) {
		return (T)get(data, key);
	}
	
	public static Object get(Map<String, Object> data, String key) {
		return get(new JsonObject(data), key);
	}
		
	public static Object get(JsonObject data, String key) {
		if (data != null) {
			if (!data.containsKey(key)) {
				Matcher m = keyPattern.matcher(key);
				
				if (m.find()) {
					String name = m.group(1);
					String index = m.group(2);
					
					key = key.replace(m.group(), "").replaceAll("^\\.", "");
					
					if ("".equals(key)) {
						Object val = null;
						
						if (index == null) {
							val = data.getValue(name);
						} else {
							val = data.getJsonArray(name).getValue(Integer.parseInt(index));
						}
						
						return val;
					} else {
						if (index == null) {
							return get(data.getJsonObject(name), key);
						} else {
							return get(data.getJsonArray(name).getJsonObject(Integer.parseInt(index)), key);
						}
					}
				}
			} else {
				return data.getValue(key);
			}
		}
		
		return null;
	}
}
